package com.ifonly.render.renders;

import com.ifonly.common.ContentTypeMapping;
import com.ifonly.config.Configuration;
import com.ifonly.render.Render;
import com.ifonly.render.RenderException;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-15 15:44
 * @since JDK 1.6
 */
public class TextRender extends Render {

    private String text;
    private String contentType;

    public TextRender(String text) {
        this(text, ContentTypeMapping.TEXT_PLAIN.contentType + CHARSET_PROP + Configuration.getInstance().getEncoding());
    }

    public TextRender(String text, String contentType) {
        this.text = text;
        this.contentType = contentType;
    }

    @Override
    public void render() {
        PrintWriter writer = null;
        try {
            // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            response.setContentType(contentType);
            response.setCharacterEncoding(Configuration.getInstance().getEncoding());

            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            throw new RenderException(e);
        }
        finally {
            if (writer != null)
                writer.close();
        }
    }
}
